package com.inspinia.upms.client.ream;

import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.common.shiro.SSOAuthToken;
import com.inspinia.auth.rpc.api.AuthService;
import com.inspinia.upms.common.model.user.UpmsUser;
import com.inspinia.upms.common.model.user.UpmsUserStatus;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author Veblen
 */
public class ClientNonceRealm extends AuthorizingRealm {

    @Resource
    private AuthService authService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        UpmsUser user = (UpmsUser) principals.getPrimaryPrincipal();
        return getAuthInfo(user);
    }

    /**
     * 获取用户的权限配置
     *
     * @param user 用户信息
     * @return
     */
    public AuthorizationInfo getAuthInfo(UpmsUser user) {
        if (user != null) {
            return authService.getAuthorizationInfo(user.getUserName(), user.getAppName());
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SSOToken ssoToken = (SSOToken) token.getPrincipal();
        UpmsUser user = authService.findById(Long.valueOf(ssoToken.getUid()));

        if (Objects.isNull(user)) {
            throw new UnknownAccountException();
        }

        //判断用是否被被冻结
        UpmsUserStatus status = user.getStatus();
        switch (status) {
            case DISABLE:
                //账户已经被冻结.
                throw new LockedAccountException();
            default:
        }
        return new SimpleAuthenticationInfo(user, token.getCredentials(), getName());
    }
    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && SSOAuthToken.class.isAssignableFrom(token.getClass());
    }
}
